package com.example.RemindMe;

import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class LocationToAddressAsync extends AsyncTask<String,String,String> {
	
	TextView t;
	 String address;
	
	public void setTextView(TextView tv)
	{
		this.t = tv;
	}
	
	@Override
	protected String doInBackground(String... arg0) {
		
		String lat = arg0[0];
		String longt = arg0[1];
		StringBuffer sb = new StringBuffer();
		try {
			BufferedReader inreader = null;
			
			//URL url = new URL("http://www.google.com");
			URL url = new URL("http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+longt+"&sensor=false");
			
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			
			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				inreader = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));
				String line;
				while ((line = inreader.readLine()) != null) {
					sb.append(line);
				}
				inreader.close();
				
				//Thread.sleep(10000); // sim. einer langsamen netzverbindung
				
			}
			conn = null;
			
		} catch (Exception e) {
			
			// TODO Auto-generated catch block
			e.printStackTrace();
			sb.append(e.getMessage());
			System.out.println("Exception");
		}
		
		return sb.toString();
		
		
	}

	@Override
	protected void onPostExecute(String result) {
		
		
		
		JSONObject json;
		JSONObject location;
		
		
		try {
			json = new JSONObject(result);	
			location = json.getJSONArray("results").getJSONObject(0);
			address = location.getString("formatted_address");
			
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			address = "the address cannot be called";
		}
		
		
	t.setText(address);
		
		
	}
	
	
	
	
}
